<template>
  <div class="main-content">

    <!--上方工具栏-->
    <div class="fx" style="margin-left: 16px;padding-top: 16px">

      <el-button plain @click="openAdd">新增部门</el-button>

      <el-button plain @click="treeExpandAll">展开/折叠</el-button>

      <el-button type="danger" plain @click="submitDelete">批量删除</el-button>

      <el-dropdown trigger="click" @command="dropDownClick">
        <el-button plain class="mgl12">更多操作</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="refreshCache">
              <span>.....</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!--页面内容-->
    <div class="fx" style="margin-left: 16px;margin-top: 12px">

      <!--左侧的树结构-->
      <div style="margin-bottom: 20px">

        <div class="fxStaCen now_select">
          <a-icon name="alert" color="#000000" style="margin-right: 16px"></a-icon>
          当前选择编辑： <span style="font-size: 14px">{{ blankStr(selectFormData.name, "") }}</span>

          <el-button v-if="selectFormData.name" style="padding: 0px;margin-left: 12px" link type="warning" icon="Menu"
                     @click="openOrgHasMenu()">
            菜单权限
          </el-button>

          <span v-if="selectFormData.name" style="color: #109eda;margin-left: 12px" class="pointer"
                @click="cancelNodeClick">取消选择</span>

        </div>

        <!--树搜索框-->
        <el-input v-model="option.filterTreeText" placeholder="输入内容自动搜索" style="width: 392px;"
                  suffix-icon="Search"/>

        <!--级联选项开关-->
        <div style="margin-top: 4px;margin-bottom: 2px">
          <el-switch
              v-model="option.treeCheckStrictly"
              class="ml-2"
              inline-prompt
              style="--el-switch-on-color: #ff4949;--el-switch-off-color: #13ce66"
              active-text="已关闭级联"
              inactive-text="已开启级联"
          />
        </div>

        <el-tree ref="menuTree"
                 node-key="id"
                 v-if="option.showMenuTree"
                 :props="{ value: 'id', label: 'name', children: 'children' }"
                 :data="option.orgDataLeft"
                 :default-expand-all="option.expandAll"
                 :expand-on-click-node="false"
                 :filter-node-method="filterTreeNode"
                 @node-click="nodeClick"
                 :check-strictly="option.treeCheckStrictly"
                 show-checkbox style="width: 360px;" highlight-current>
          <template #default="{ node, data }">
            <div> {{ node.label }}</div>
          </template>

        </el-tree>
      </div>

      <!--右侧内容-->
      <el-form class="fx1" ref="formDataRef" :model="selectFormData" :rules="formRules" label-width="100"
               style="margin-left: 24px">

        <el-form-item v-if="selectFormData.type!='F'" label="上级部门" prop="pid">
          <el-tree-select
              placeholder="默认根节点（输入名称搜索）"
              :disabled="!selectFormData.id"
              style="width: 400px"
              v-model="selectFormData.pid"
              :data="option.orgData"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              @node-click="treeSelect"
              check-strictly
              filterable
              :filter-node-method="treeSelectNodeFilter"
          >
            <template #default="{ node, data }">
              <div>{{ node.label }}</div>
            </template>

          </el-tree-select>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input :disabled="!selectFormData.id" v-model="selectFormData.name" placeholder="请输入名称"
                    style="width: 400px"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="selectFormData.sort" controls-position="right" :min="0" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="数据权限" prop="res">
          <el-input v-model="selectFormData.res" maxlength="2000"
                    placeholder="请输入拥有的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"/>
        </el-form-item>

        <el-form-item label="排除权限" prop="resExclude">
          <el-input v-model="selectFormData.resExclude" maxlength="2000"
                    placeholder="请输入排除的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"/>
        </el-form-item>

        <el-form-item v-if="selectFormData.type!=''">
          <el-button type="primary" @click="submitUpdate" :disabled="!selectFormData.id">修改并保存</el-button>
        </el-form-item>

      </el-form>

    </div>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="680"
               @close="dialogClose" :close-on-click-modal="false" draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="100">

        <el-form-item label="上级部门" prop="pid">
          <el-tree-select
              style="width: 400px;"
              placeholder="默认根节点（输入名称搜索）"
              v-model="formData.pid"
              :data="option.orgData"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              @node-click="treeSelect"
              filterable
              :filter-node-method="treeSelectNodeFilter"
              check-strictly
          >
            <template #default="{ node, data }">
              <div>{{ node.label }}</div>
            </template>
          </el-tree-select>
        </el-form-item>

        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" controls-position="right" :min="0" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="数据权限" prop="res">
          <el-input v-model="formData.res" maxlength="2000" placeholder="请输入拥有的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"/>
        </el-form-item>

        <el-form-item label="排除权限" prop="resExclude">
          <el-input v-model="formData.resExclude" maxlength="2000"
                    placeholder="请输入排除的数据权限（逗号分隔，禁止输入换行符）"
                    show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" style="width: 400px" type="textarea"/>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="option.openDialog=false">取 消</el-button>
        <el-button type="primary" @click="submitAdd">保 存</el-button>
      </template>

    </el-dialog>

    <!-- 编辑部门菜单 -->
    <el-dialog title="编辑部门菜单权限" v-model="option.openMenuDialog" width="1200" :close-on-click-modal="false"
               draggable
               append-to-body destroy-on-close>

      <SelectMenu ref="selectMenu" @call-back="selectMenuCallBack"
                  :default-checked="option.defaultChecked"></SelectMenu>

      <template #footer>
        <el-button @click="()=>{option.openMenuDialog=false}">关 闭</el-button>
        <el-button type="primary" @click="proxy.$refs.selectMenu.returnCheckData();">保 存</el-button>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>
import {getCurrentInstance, nextTick, onMounted, ref, watch} from "vue";
import {
  apiMenuRefreshCache,
  apiOrgDelete,
  apiOrgInsert,
  apiOrgUpdate,
  apiRoleMenuUpdate,
  apiUserHasOrg
} from "@/api/system";
import {blankStr, copyNew, parseTree} from "@/common/utils/kit";
import $modal from "@/common/utils/modal";
import SelectMenu from "@/view/sys/selectMenu";

const {proxy} = getCurrentInstance();

let optionKey = {
  treeCheckStrictly: false,
  dialogTitle: "",
  openDialog: false,
  loading: false,
  orgDataLeft: [],
  orgData: [],
  expandAll: false,
  showMenuTree: true,
  disabledD: false,
  disabledM: false,
  disabledF: false,
  filterTreeText: '',
  alertTitle: '',
  defaultChecked: [],
}

let formKey = {
  id: "",
  pid: "0",
  level: 0,
  name: "",
  routePath: "",
  filePath: "",
  type: "D",
  sort: 100,
  res: "",
  linkType: "0",
  linkUrl: "",
  resExclude: "",
  functionKey: "",
  menuIds: [],
}

const formRules = ref({
  functionKey: [{required: true, message: "不能为空", trigger: "blur"}],
  type: [{required: true, message: "不能为空", trigger: "change"}],
  sort: [{required: true, message: "不能为空", trigger: "blur"}],
  name: [{required: true, message: "不能为空", trigger: "blur"}],
  routePath: [{required: true, message: "不能为空", trigger: "blur"}],
  filePath: [{required: true, message: "不能为空", trigger: "blur"}],
  menuName: [{required: true, message: "不能为空", trigger: "blur"}],
  orderNum: [{required: true, message: "不能为空", trigger: "blur"}],
  pid: [{required: true, message: "不能为空", trigger: "blur"}],
  linkType: [{required: true, message: "不能为空", trigger: "blur"}],
  linkUrl: [{required: true, message: "不能为空", trigger: "blur"}],
  path: [{required: true, message: "不能为空", trigger: "blur"}]
});
const option = ref(optionKey);
const formData = ref(formKey);
const selectFormData = ref(formKey);

function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSelectForm() {
  selectFormData.value = copyNew(formKey);
}

//页面加载完成回调
onMounted(() => {
  selectAllOrg()
})

watch(option.value, (val) => {
  if (proxy.$refs["menuTree"]) {
    proxy.$refs["menuTree"].filter(val.filterTreeText)
  }
})

//dialog销毁回调
function dialogClose() {
  //console.log("dialog销毁回调")
  formData.value = copyNew(selectFormData.value)
}

//上级目录下拉选
function treeSelect(value) {
  let level = 0;
  if (value.level) {
    level = value.level * 1 + 1;
  }
  formData.value.level = level
  if (level == '0' || level == '1') formData.value.type = "D"
  if (level == '2') formData.value.type = "M"
  if (level == '3') formData.value.type = "F"
  console.log(" formData..level ", formData.value.level)
  console.log(" formData..type ", formData.value.type)
}

const treeSelectNodeFilter = (value, data) => {
  return data.name.includes(value)
}

// 菜单树选中事件
function nodeClick(row) {
  formData.value = JSON.parse(JSON.stringify(row));
  selectFormData.value = JSON.parse(JSON.stringify(row));
}

// 菜单树取消选中事件
function cancelNodeClick() {
  resetForm()
  resetSelectForm()
}

// 打开部门具备的菜单权限
function openOrgHasMenu() {
  option.value.defaultChecked = selectFormData.value.menuIds;
  option.value.nowOrgId = selectFormData.value.id;
  option.value.openMenuDialog = true;
}

function selectMenuCallBack(data) {
  console.log("selectMenuCallBack ", data.checkedNodes.length)

  let menuIds = []
  data.checkedNodes.filter(e => {
    menuIds.push(e.id)
  });
  ////console.log("option.value.nowRoleId ", option.value.nowRoleId)
  ////console.log("menuIds ", menuIds)
  apiRoleMenuUpdate({roleId: option.value.nowRoleId, menuIds: menuIds.join(",")}).then(res => {
    if (res.success) {
      option.value.nowRoleId = 0
      option.value.openMenuDialog = false
      $modal.success()
      searchData()
    }
  })
}

// 菜单树过滤时间
function filterTreeNode(value, data) {
  if (!value) return true
  return data.name.includes(value)
}

// 全部展开折叠事件
function treeExpandAll() {
  let checkedKeys = proxy.$refs["menuTree"].getCheckedKeys();

  option.value.showMenuTree = false;
  option.value.expandAll = !option.value.expandAll
  nextTick(() => {
    option.value.showMenuTree = true;
    nextTick(() => {
      proxy.$refs["menuTree"].setCheckedKeys(checkedKeys);
    });

  });

}

//查询菜单数据
async function selectAllOrg() {
  let res = await apiUserHasOrg()
  option.value.orgDataLeft = parseTree(res.data);
  option.value.orgData = parseTree(res.data);
  option.value.orgData.unshift({id: "0", name: '根节点'})
}

//更多操作
function dropDownClick(command) {
  switch (command) {
    case "refreshCache":
      apiMenuRefreshCache().then((res) => {
        if (res.success) {
          $modal.success();
        }
      })
      break;
    default:
      break;
  }
}

/** 新增功能操作 */
function openAdd() {
  console.log("【新增部门】 ", formData.value)

  //在当前登层级下创建
  if (formData.value.id) {
    let pid = "" + formData.value.id
    let level = "" + formData.value.level
    resetForm();
    formData.value.pid = pid
    formData.value.level = level * 1 + 1
  }
  //
  else {
    resetForm();
  }
  option.value.dialogTitle = "新增部门";
  option.value.openDialog = true;
}

/** 提交功能 */
async function submitAdd() {
  proxy.$refs["formDataRef"].validate(async valid => {
    //console.log(" option.value.expandAll ", option.value.expandAll)

    if (valid) {
      if (formData.value.pid == "0") formData.value.level = 0;
      let res = await apiOrgInsert(formData.value)
      if (res.success) {
        $modal.success();
        await selectAllOrg(formData.value)
        option.value.openDialog = false;
        formData.value = copyNew(selectFormData.value)
        //console.log("  formData.value ", formData.value)
        //console.log(" option.value.expandAll ", option.value.expandAll)
      }
      //console.log(res)
    }

  });
}

async function submitUpdate() {
  if (!selectFormData.value.id) {
    $modal.warning("请选选择一条数据");
    return;
  }

  proxy.$refs["formDataRef"].validate(async valid => {
    if (valid) {
      $modal.confirmWarning('正在修改菜单数据，是否继续操作？')
          .then(async () => {
            let res = await apiOrgUpdate(selectFormData.value)
            // //console.log(res)
            if (res.success) {
              $modal.success();
              await selectAllOrg()
            }
          })
          .catch(() => {
            $modal.cancel();
          });
    }
  });
}

/** 删除功能操作 */
function submitDelete(row) {
  let checkedNodes = proxy.$refs["menuTree"].getCheckedNodes();
  if (checkedNodes.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  let ids = [];
  let names = [];
  checkedNodes.filter(e => {
    ids.push(e.id)
    names.push(e.name)
  })
  //console.log(ids)
  let content = `正在删除名称为【 ${names.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        let res = await apiOrgDelete({ids: ids.join(",")})
        if (res.success) {
          $modal.success();
          cancelNodeClick();
          await selectAllOrg()
        }
      }).catch(() => $modal.cancel());
}

</script>

<style scoped lang="less">
.now_select {
  font-size: 14px;
  background: #FFF3F1;
  border-radius: 4px;
  border: 1px solid #ffd9d4;
  padding: 9px;
  margin-bottom: 12px
}

.SZ {
  zoom: 0.8;
}

.D {
  font-size: 16px;
  color: #c57d11;
  //border: 1px dashed #c57d11;
}

.M {
  font-size: 16px;
  color: #109eda;
  //border: 1px dashed #109eda;
}

.FF {
  font-size: 16px;
  color: #7ecb2d;
  //border: 1px dashed #109eda;
}

.FFF {
  color: #7ecb2d;
  font-size: 13px;
  border: 1px solid #57d753;
  border-radius: 14px;
  padding: 2px 10px;
}
</style>